import { NextResponse } from 'next/server';
import { verifyToken } from '@/utils/auth';
import UserModel from '@/models/user';

// POST 请求处理器 - 标记简历申请为已读
export async function POST(
  request: Request, 
  { params }: { params: { id: string; applicationId: string } }
) {
  try {
    // 验证用户身份
    const authHeader = request.headers.get('authorization');
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }

    const token = authHeader.split(' ')[1];
    const payload = verifyToken(token);

    if (!payload || !payload.id) {
      return NextResponse.json({ error: '无效的令牌' }, { status: 401 });
    }

    const userId = payload.id;
    const jobPostId = parseInt(params.id);
    const applicationId = parseInt(params.applicationId);

    if (isNaN(jobPostId) || isNaN(applicationId)) {
      return NextResponse.json({ error: '无效的ID参数' }, { status: 400 });
    }

    // 首先验证这个招聘公告是否属于当前用户
    const [jobPosts] = await UserModel.query<any[]>(
      `SELECT id FROM job_positions WHERE id = ? AND created_by = ?`,
      [jobPostId, userId]
    );

    if (!jobPosts || jobPosts.length === 0) {
      return NextResponse.json({ error: '招聘公告不存在或您无权操作' }, { status: 403 });
    }

    // 验证简历申请是否存在且属于该招聘公告
    const [applications] = await UserModel.query<any[]>(
      `SELECT id FROM resume_submissions WHERE id = ? AND position_id = ?`,
      [applicationId, jobPostId]
    );

    if (!applications || applications.length === 0) {
      return NextResponse.json({ error: '简历申请不存在' }, { status: 404 });
    }

    // 更新简历申请的已读状态
    await UserModel.query(
      `UPDATE resume_submissions SET is_read = 1 WHERE id = ?`,
      [applicationId]
    );

    console.log(`标记简历已读: 用户ID=${userId}, 招聘公告ID=${jobPostId}, 申请ID=${applicationId}`);

    return NextResponse.json({ 
      success: true, 
      message: '简历已标记为已读',
      data: {
        jobPostId,
        applicationId,
        userId
      }
    });
  } catch (error) {
    console.error('标记简历已读失败:', error);
    return NextResponse.json(
      { error: `标记简历已读失败: ${(error as Error).message}` },
      { status: 500 }
    );
  }
} 